// pages/Users/UpTopBalance/UpTopBalance.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getTopUpConfig , getChannel , requestTopUp } from '../../../api/brand';
import { getUserAccount , queryUserWechatOpenId } from '../../../api/user';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareTitle: app.globalData.global.shareTitle,
    // navBgColor: 'linear-gradient(to right,rgb(20, 172, 105),rgb(62, 214, 147))',
    navBgColor: '#FFFFFF',
    tabNavTop: app.globalData.CustomBar,
    assetsAddress: assetsAddress,
    configList: [], // 充值配置
    channelTag: '', // 微信充值tag
    topUpConfigId: '',
    openid: '',
    number: '', // 充值金额
    rate: 0, // 充值渠道手续费
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._getTopUpConfig();
    this._getChannel();
    this._getUserAccount();
    this._queryUserWechatUnionId();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this._getTopUpConfig();
    this._getChannel();
    this._getUserAccount();
    setTimeout(()=>{
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res,'刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 返回上一页
  back(){
    wx.navigateBack({
      delta: 1,
    })
  },
  // 获取充值配置
  _getTopUpConfig(){
    let _this = this;
    getTopUpConfig()
    .then(res => {
      if(res.success){
        _this.setData({
          configList: res.data.content,
        })
        if(res.data.content.length > 0){
          _this.setData({
            topUpConfigId: res.data.content[0].id
          })
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取通道配置
  _getChannel(){
    let _this = this;
    getChannel({isOn: '1'})
    .then(res => {
      if(res.success){
        var channelTag = '';
        var rate = 0;
        let array = res.data.content;
        for (let index = 0; index < array.length; index++) {
          const item = array[index];
          if(item.channelName.indexOf('微信') != -1 && item.channelName.indexOf('支付') != -1){
            channelTag = item.channelTag;
            rate = item.rate;
          }
        }
        _this.setData({
          channelTag: channelTag,
          rate: rate,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户余额信息
  _getUserAccount(){
    let _this = this;
    getUserAccount()
    .then(res => {
      if(res.success){
        _this.setData({
          balance: res.data.balance,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 确认充值
  submit(){
    let _this = this;
    if(_this.data.channelTag == ''){
      wx.showToast({
        title: '暂无可以支付渠道！',
        icon: 'none',
      })
      return;
    }
    if(_this.data.number == ''){
      wx.showToast({
        title: '请输入充值金额',
        icon: 'none',
      });
      return;
    }
    requestTopUp({channelTag: _this.data.channelTag,openId: _this.data.openid,number: _this.data.number})
    .then(res => {
      if(res.success){
        var order = JSON.parse(res.data.data)
        // TODO微信支付
        wx.requestPayment({
          timeStamp: order.timeStamp.toString(),
          nonceStr: order.nonceStr,
          package: order.package,
          signType: order.signType,
          paySign: order.paySign,
          success: () => {
            wx.showToast({
              title: '充值成功',
              icon: 'success'
            })
            _this._getUserAccount();
            wx.navigateTo({
              url: '/pages/Earnings/UpTopBalanceBill/UpTopBalanceBill',
            })
          },
          fail: (err) => {
            console.log(err,'err')
            wx.showToast({
              title: '取消支付',
              icon: 'none',
            })
          }
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 选择充值金额
  selUpTop(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    this.setData({
      topUpConfigId: item.id,
    })
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(JSON.stringify(url,'url'))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              openid: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
})